package com.edais.service.imp;

import com.edais.dao.*;
import com.edais.domain.*;
import com.edais.domain.zftPay.FastPayTokenParamters;
import com.edais.domain.zftPay.PayParamtersTemp;
import com.edais.rabbit.RabbitUtil;
import com.edais.service.CaptchaService;
import com.edais.service.ErrorMessageService;
import com.edais.service.SMSService;
import com.edais.service.ThirdProductRouteService;
import com.edais.service.WeixinBindingService;
import com.edais.util.*;
import com.edais.util.weixinAbout.SendWeiXinUtil;
import com.lb.sssq.util.JsonUtil;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultDTO;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ThirdProductRouteServiceImpl implements ThirdProductRouteService {
	private static final Logger logger = Logger
			.getLogger(ThirdProductRouteServiceImpl.class);
	@Autowired
	private ThirdProductRouteDao thirdProductRouteDao;
	
	@Autowired
	private SMSService sMSService;
	
	@Autowired
	RabbitUtil rabbitUtil;
	
	@Autowired 
	private UserDao userDao;
	
	@Autowired
	private UserCardDao userCardDao;
	
	@Autowired
	private ErrorMessageService errorMessageService;
	
	@Autowired
	private CenterDao centerDao;
	
	@Autowired
	private PayDao payDao;
	
	@Autowired
	private BankDao bankDao;
	@Autowired
	private CaptchaService captchaService;

	@Autowired
	private UserExtractInfoDao userExtractInfoDao;
	
	@Autowired
	private WeixinBindingService weixinBindingService;
	/*
	 * (non-Javadoc)
	 * @see
	 * com.edais.service.ThirdProductRouteService#getThirdProductRoutes(java
	 * .util.Map)
	 */
	@Override
	public List<ThirdProductRoute> getThirdProductRoutes(
			Map<String, String> paramMap) {
		return thirdProductRouteDao.getThirdProductRoutes(paramMap);
	}
	
	private final static BigDecimal ONE_HUNDRED = new BigDecimal("100");
	
	/**
	 * 1元等于100分
	 * @param  Yuan 元
	 * @return Feng 分整数字符
	 */
	private String getFeng(String Yuan) {
		return String.valueOf(new BigDecimal(Yuan).multiply(ONE_HUNDRED).longValue());
	}
	
	/**
	 * 根据银行名称获取快速提现路由
	 * @param bankName
	 * @param productCode
	 * @return
	 */
	@Override
	public List<ThirdProductRoute> getThirdProductRoutes(String bankName, String productCode) {
		Map<String, String> queryRouteMap = new HashMap<String, String>();
		queryRouteMap.put("bankName", bankName);
		queryRouteMap.put("productCode", productCode);
		List<ThirdProductRoute> thirdProductRoutes = this.getThirdProductRoutes(queryRouteMap);
		return thirdProductRoutes;
	}

	/**
	 * 根据银行名称获取第三方平台银行
	 * @param bankName
	 * @param thirdPlatformCode
	 * @return
	 */
	public ThirdPlatformBank getThirdPlatFormBank(String bankName, String thirdPlatformCode) {
		Map<String, String> queryThirdBankMap = new HashMap<String, String>();
		queryThirdBankMap.put("bankName", bankName);
		queryThirdBankMap.put("thirdPlatformCode", thirdPlatformCode);
		ThirdPlatformBank thirdPlatformBank = thirdProductRouteDao.getThirdPlatformBank(queryThirdBankMap);
		return thirdPlatformBank;
	}

	/* (non-Javadoc)
	 * @see com.edais.service.ThirdProductRouteService#quickWithDraw(java.util.Map)
	 */
	/* (non-Javadoc)
	 * @see com.edais.service.ThirdProductRouteService#quickWithDraw(java.util.Map, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	@Async
	public Map<String, String> quickWithDraw(Map<String, Object> withDrawApply, String thirdProductCode, String thirdBankCode, String extractPlatform, String thirdPlatformCode,String bankName) {
		Map<String,String> resultMap = new HashMap<String,String>();
		String logInfo = "快速提现" + withDrawApply.get("reqOrderId") + "-";
		String applyId = withDrawApply.get("applyId").toString();
		String reqOrderId = withDrawApply.get("reqOrderId").toString();
		String tranAmount = withDrawApply.get("extractFeePay").toString();//实际金额
		String accountProp = withDrawApply.get("publicPrivate").toString(); // 账号属性 0私人，1公司
		String accountType = withDrawApply.get("receAcctType").toString();  // 账号类型00银行卡，01存折，02信用卡。不填默认为银行卡00
		String bankAccountNo = withDrawApply.get("extractCardNo").toString();
		String bankAccountName = withDrawApply.get("userName").toString();
		String userId = withDrawApply.get("userId").toString();
		String identityNo = withDrawApply.get("identityNo").toString();
		String phoneNumber = withDrawApply.get("phoneNo").toString();
		String extractMoney = withDrawApply.get("extractMoney").toString();//提现金额
		String extractFee = withDrawApply.get("extractFee").toString();//提现手续费
		// 调用ThirdParty发起提现
		Map<String, String> map = new HashMap<String, String>();
		map.put("reqOrderId", reqOrderId); // 商户订单号
		map.put("reqDateTime", DateUtil.getCurrentDateStr1()); // 商户订单时间
		map.put("tranAmount", this.getFeng(tranAmount)); // 代付金额（以分为单位）
		map.put("accountFlag", accountProp);         // 对公/对私标识
		map.put("accountType", accountType);         // 账号类型 00银行卡
		map.put("bankAccountNo", bankAccountNo);     // 银行卡卡号
		map.put("bankAccountName", bankAccountName); // 银行卡账户名称
		map.put("orderDesc", reqOrderId); // 订单描述 
		map.put("userId", userId);                // 用户ID
		map.put("identityNo", identityNo);        // 身份证号码
		map.put("phoneNumber", phoneNumber);      // 手机号码
		map.put("bankCode", thirdBankCode);       // 银行编码
		map.put("bankName", bankName); // 银行名称
		map.put("productCode", thirdProductCode); // 第三方产品代码
		if("quick_withdraw_changjie".equals(thirdProductCode)){//畅捷提现提供12位人行编码
			Bank bank = bankDao.queryBankByName(bankName);
			logger.info(logInfo +"-javaservice-quick_withdraw_changjie-GetBankCode12：" + bank.getPbc_code());
			map.put("bankCode", bank.getPbc_code());
		}
		Map<String, String> resMap = ThirdPartyEnvUtil.invoke(logInfo, map, "/route/withdraw");
		// 更新核心提现记录
		String resCode = resMap.get("rescode");
		String resMessage = resMap.get("resmsg_cn");
		String resOrderId = reqOrderId;
		String sendMessage = "";
		if(resMap.containsKey("sendMessage")) {
			sendMessage = resMap.get("sendMessage");
		}
		String receiveMessage = "";
		if(resMap.containsKey("receiveMessage")) {
			receiveMessage = resMap.get("receiveMessage");
		}
		String status = "";
		String message = "";
		try{
			if (resCode.equals("00001")) {
				status = "2";
				message = "交易成功";
				// 成功逻辑，发送短信给客户
				logger.info(logInfo + "交易成功");
				sMSService.sendSMS(logInfo, phoneNumber, "sms05001", bankAccountName,extractMoney,extractFee,tranAmount);
				//发送个推消息----add by gongyanlan
				String smsNo="sms05001";//提现,config_sms表中参数,
				String mobile = captchaService.getMobileById(userId);//通过用户ID查询使用手机号
				String[] smsParams={"",extractMoney,extractFee,tranAmount};
				Map<String,Object> paramMap=new HashMap<String,Object>();
				paramMap.put("userId", userId);
				paramMap.put("mobile", mobile);
				paramMap.put("title", "提现成功通知");//标题
				paramMap.put("messageDetailTypeNew", "5");//1.订制商品个人消息，2.还款成功，3.充值，4.投资，5,提现
				paramMap.put("messageDetailResult", "0");//0.执行成功消息提示，1.执行失败提示
				paramMap.put("smsParams", smsParams);//消息模板里需要替换的变量
				paramMap.put("smsNo", smsNo);
				sMSService.sendGetuiMSG(paramMap);
			} else if (resCode.equals("00002")) {
				status = "3";
				message = "交易失败";
				// 失败逻辑，发送运营人员
				logger.info(logInfo + "交易失败" + "-" + resMessage);
				sMSService.sendSMS(logInfo, phoneNumber, "sms05003", "");
				sMSService.sendErrorMessageForSystem("sms05004","",phoneNumber, reqOrderId, resMessage,productCodeToString(thirdProductCode)+"-"+bankName);
			} else if (resCode.equals("00003")) {
				status = "4";
				message = "交易处理中";
				logger.info(logInfo + "交易处理中");
			} else if (resCode.equals("00004")) {
				status = "6";
				message = resMessage;
				logger.info(logInfo + "交易异常，请联系管理员" + "-" + resMessage);
				// 异常逻辑，发送短信给运营人员
				sMSService.sendErrorMessageForSystem("sms05004","",phoneNumber, reqOrderId, resMessage,productCodeToString(thirdProductCode)+"-"+bankName);
				sMSService.sendErrorMessageForUser("sms05002",phoneNumber, bankAccountName);
			}
		} catch(Exception e) {
			logger.error(logInfo + "发送运营短信异常", e);
		}
		
		this.updateExtractApply(userId, applyId, reqOrderId, status, message,
				sendMessage, receiveMessage, resOrderId, extractPlatform, userId, phoneNumber, extractMoney);
		resultMap.put("rescode", Consts.SUCCESS_CODE);
		resultMap.put("resmsg_cn", "提现申请发送成功！");
		
		// 发送延迟消息队列，5分钟后，重新查询结果，通联、中信和畅捷需要延迟队列
		if(("3".equals(extractPlatform) || "4".equals(extractPlatform) || "5".equals(extractPlatform)) 
				&& ("4".equals(status) || "6".equals(status))) {
			Map<String, String> jsonMap = new HashMap<String, String>();
			jsonMap.put("reqOrderId", reqOrderId);
			jsonMap.put("productCode", "queryresult_" + thirdPlatformCode);
			jsonMap.put("userId", userId);
			jsonMap.put("phoneNumber", phoneNumber);
			jsonMap.put("tranAmount", tranAmount);
			jsonMap.put("queryCount", "1");
			jsonMap.put("extractMoney", extractMoney);
			jsonMap.put("extractFee", extractFee);
			jsonMap.put("bankAccountName", bankAccountName);
			rabbitUtil.convertAndSend(logInfo, RabbitUtil.DELAY_5M_QUENE, JsonUtil.getJsonStringFromMap(jsonMap), phoneNumber, reqOrderId);
		}
		
		return resultMap;
	}

	/**
	 * 更新核心提现记录
	 * 
	 * @param sysUserId    操作人ID
	 * @param applyId      提现申请表ID
	 * @param reqOrderId   上送订单号
	 * @param handleStatus 第三方处理结果
	 * @param rtnMsg       第三方返回信息
	 * @param sendMessage  上送报文
	 * @param rcvMessage   返回报文
	 * @param tradeNo      第三方订单号
	 * @param extractPlatform 提现平台 
	 * @param applyUserId     申请人ID
	 * @return
	 * @throws Exception 
	 */
	public String updateExtractApply(String sysUserId, String applyId,
			String reqOrderId, String handleStatus, String rtnMsg,
			String sendMessage, String rcvMessage, String tradeNo,
			String extractPlatform, String applyUserId,String phoneNumber, String extractMoney){
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("applyId", applyId);           // 提现申请表ID
		params.put("reqOrderId", reqOrderId);     // 上送订单号
		params.put("handleStatus", handleStatus); // 第三方处理结果
		params.put("rtnMsg", rtnMsg);             // 第三方返回信息
		params.put("sendMessage", sendMessage);   // 上送报文
		params.put("rcvMessage", rcvMessage);     // 返回报文
		params.put("tradeNo", tradeNo);           // 第三方订单号
		params.put("extractPlatform", extractPlatform); //提现平台 1连连 2掌上汇通 3通联 4中信 -1未知
		params.put("applyUserId", applyUserId);         // 申请人ID
		params.put("mediaType", "1");         // 区分前后台，后台无须扣减提现次数 0后台 1手机 
		String req = "";
		String res = "";
		String logInfo = "快速提现" + reqOrderId;
		try {
			req = CommonUtil.constructJsonStr("E310066", sysUserId, params);
			logger.info(logInfo + "更新核心提现记录开始" + req);
			res = CommonUtil.getCoreValue(req);
			logger.info(logInfo + "更新核心提现记录结束" + res);
			JSONObject resJson = JSONObject.fromObject(res);
			String rescode = resJson.get("rescode").toString();
			if (rescode.equals(Consts.SUCCESS_CODE)) {
				logger.info(logInfo + "同步更新提现为成功");
			} else if (rescode.equals("99998")) {
				// add by aohujun start
				UserExtractInfo userExtractInfo = new UserExtractInfo();
				userExtractInfo.setUserId(Integer.valueOf(applyUserId));
				userExtractInfo.setExtractAmount(new BigDecimal(extractMoney));
				int result = userExtractInfoDao.returnQuickUserExtractInfo(userExtractInfo);
				logger.info(logInfo + "同步更新提现为失败，退还快速提现次数及金额：" + result);
				// add by aohujun end
			} else if (rescode.equals("99997")){
				logger.info(logInfo + "同步更新时，记录已修改，异步可能比同步快");
			} else {
				logger.info(logInfo + "同步更新时，核心返回状态异常：" + rescode);
				sMSService.sendErrorMessageForSystem("sms05004","",phoneNumber, reqOrderId, "核心更新异常");
			}
		} catch (Exception e) {
			logger.error(logInfo + "更新核心提现记录异常", e);
			try {
				sMSService.sendErrorMessageForSystem("sms05004","",phoneNumber, reqOrderId, e.getMessage());
			} catch (Exception e1) {
				logger.error(logInfo + "发送运营短信异常", e1);
			}
			return null;
		}
		return res;
	}
	
	@Override
	public Map<String, String> queryResult(Map<String, Object> queryResultMap) throws Exception {
		Map<String,String> rtnMap = new HashMap<String,String>();
		String logInfo = "查询订单" + queryResultMap.get("reqOrderId") + "-";
		
		String reqOrderId = queryResultMap.get("reqOrderId").toString();
		String productCode = queryResultMap.get("productCode").toString();
		String userId = queryResultMap.get("userId").toString();
		String phoneNumber = queryResultMap.get("phoneNumber").toString();
		String tranAmount = queryResultMap.get("tranAmount").toString();
		String queryCount = queryResultMap.get("queryCount").toString();
		String extractFee = queryResultMap.get("extractFee").toString();
		String extractMoney = queryResultMap.get("extractMoney").toString();
		String bankAccountName = queryResultMap.get("bankAccountName").toString();
		
		// 调用ThirdParty发起提现
		Map<String, String> map = new HashMap<String, String>();
		map.put("reqOrderId", reqOrderId); // 商户订单号
		map.put("productCode", productCode);
		
		Map<String, String> resMap = ThirdPartyEnvUtil.invoke(logInfo, map, "/route/query");
		String status = "";
		String message = "";
		String resCode = resMap.get("rescode");
		String resMessage = resMap.get("resmsg_cn");
		
		if (resCode.equals("00001")) {
			status = "2";
			message = "交易成功";
			// 成功逻辑，发送短信给客户
			logger.info(logInfo + "交易成功");
			//发送个推消息----add by gongyanlan
			String smsNo="sms05001";//提现,config_sms表中参数,
			String mobile = captchaService.getMobileById(userId);//通过用户ID查询使用手机号
			sMSService.sendSMS(logInfo, mobile, "sms05001",bankAccountName, extractMoney,extractFee,tranAmount);  
			String[] smsParams={"",extractMoney,extractFee,tranAmount};
			Map<String,Object> paramMap=new HashMap<String,Object>();
			paramMap.put("userId", userId);
			paramMap.put("mobile", mobile);
			paramMap.put("title", "提现成功通知");//标题
			paramMap.put("messageDetailTypeNew", "5");//1.订制商品个人消息，2.还款成功，3.充值，4.投资，5,提现
			paramMap.put("messageDetailResult", "0");//0.执行成功消息提示，1.执行失败提示
			paramMap.put("smsParams", smsParams);//消息模板里需要替换的变量
			paramMap.put("smsNo", smsNo);
			sMSService.sendGetuiMSG(paramMap);
		} else if (resCode.equals("00002")) {
			status = "3";
			message = "交易失败";
			// 失败逻辑，发送运营人员
			logger.info(logInfo + "交易失败" + "-" + resMessage);
			sMSService.sendSMS(logInfo, phoneNumber, "sms05003", "");
			sMSService.sendErrorMessageForSystem("sms05004","",phoneNumber, reqOrderId, resMessage,productCodeToString(productCode));
		} else if (resCode.equals("00003")) {
			status = "4";
			message = "交易处理中";
			logger.info(logInfo + "交易处理中");
		} else if (resCode.equals("00004")) {
			status = "6";
			message = resMessage;
			logger.info(logInfo + "交易异常，请联系管理员" + "-" + resMessage);
		}
		
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put("reqOrderId", reqOrderId);
		jsonMap.put("productCode", productCode);
		jsonMap.put("userId", userId);
		jsonMap.put("phoneNumber", phoneNumber);
		jsonMap.put("tranAmount", tranAmount);
		jsonMap.put("extractMoney", extractMoney);
		jsonMap.put("extractFee", extractFee);
		// 发送延迟消息队列，30分钟后，重新查询结果
		if("1".equals(queryCount) && ("4".equals(status) || "6".equals(status))) {
			jsonMap.put("queryCount", "2");
			rabbitUtil.convertAndSend(logInfo, RabbitUtil.DELAY_30M_QUENE, JsonUtil.getJsonStringFromMap(jsonMap), phoneNumber, reqOrderId);
			// 中信银行发起快速提现时几乎不会失败，故需要在状态为6时通知运营人员
			if ("queryresult_zhongxinbank".equals(productCode) 
					&& "6".equals(status)) {
				sMSService.sendErrorMessageForSystem("sms05004","",phoneNumber, reqOrderId, resMessage, productCodeToString(productCode));
			}
		} else if ("2".equals(queryCount) && ("4".equals(status) || "6".equals(status))) {
			//发送延迟消息队列，2小时后，重新查询结果
			jsonMap.put("queryCount", "3");
			rabbitUtil.convertAndSend(logInfo, RabbitUtil.DELAY_120M_QUENE, JsonUtil.getJsonStringFromMap(jsonMap), phoneNumber, reqOrderId);
		}
		
		if("2".equals(status) || "3".equals(status)){
			String transCode = "E300054";
			Map<String, Object> paramsMap = new HashMap<String, Object>();
			String resultPay = "FAILD";
			
			if("2".equals(status) ){
				resultPay = "SUCCESS";
			}
			String noOrder = reqOrderId;
			String oidPaybill = reqOrderId;
			paramsMap.put("resultPay", resultPay);
			paramsMap.put("noOrder", noOrder);
			paramsMap.put("oidPaybill", oidPaybill);
			paramsMap.put("moneyOrder", tranAmount);
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
			paramsMap.put("dtOrder", sdf1.format(new Date()));
			paramsMap.put("settleDate", sdf2.format(new Date()));
			
			String jsonStr = CommonUtil.constructJsonStr(transCode, null, paramsMap);
			String rtnStr = CommonUtil.getCoreValue(jsonStr);
			JSONObject jsonObject = JSONObject.fromObject(rtnStr);
			String rescode = jsonObject.getString("rescode");
			
			if (rescode.equals(Consts.SUCCESS_CODE)) {
				rtnMap.put("rescode", Consts.SUCCESS_CODE);
				rtnMap.put("resmsg_cn", Consts.SUCCESS_DESCRIBE);
			}else if(rescode.equals("99998")){
				// add by aohujun start
				if ("3".equals(status)) {
					UserExtractInfo userExtractInfo = new UserExtractInfo();
					userExtractInfo.setUserId(Integer.valueOf(userId));
					userExtractInfo.setExtractAmount(new BigDecimal(extractMoney));
					int result = userExtractInfoDao.returnQuickUserExtractInfo(userExtractInfo);
					logger.info(logInfo + "rabbit查询到提现失败，退还快速提现次数及金额：" + result);
				}
				// add by aohujun end
				rtnMap.put("rescode", Consts.SUCCESS_CODE);
				rtnMap.put("resmsg_cn", Consts.SUCCESS_DESCRIBE);
			}  else if(rescode.equals("99997")){
				rtnMap.put("rescode", Consts.SUCCESS_CODE);
				rtnMap.put("resmsg_cn", Consts.SUCCESS_DESCRIBE);
			}else {
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg_cn", "提现回调更新信息失败！");
				sMSService.sendErrorMessageForSystem("sms05004","",phoneNumber, reqOrderId, "提现回调更新信息失败！",productCodeToString(productCode));
			}
			
		}else{
			rtnMap.put("rescode", Consts.SUCCESS_CODE);
			rtnMap.put("resmsg_cn", Consts.SUCCESS_DESCRIBE);
		}
		
		return rtnMap;
	}
	
	public String productCodeToString(String thirdProductCode){
		String productCodeStr = "";
		if("quick_withdraw_tonglian".equals(thirdProductCode) || "queryresult_tonglian".equals(thirdProductCode)){
			productCodeStr = "通联";
		}else if ("quick_withdraw_payplam".equals(thirdProductCode) || "queryresult_payplam".equals(thirdProductCode)){
			productCodeStr = "掌上汇通";
		}else if ("quick_withdraw_zhongxinbank".equals(thirdProductCode) || "queryresult_zhongxinbank".equals(thirdProductCode)){
			productCodeStr = "中信";
		}else if ("quick_withdraw_changjie".equals(thirdProductCode) || "queryresult_changjie".equals(thirdProductCode)){
			productCodeStr = "畅捷";
		}else if ("quick_withdraw_fuyoudsf".equals(thirdProductCode) || "queryresult_fuyoudsf".equals(thirdProductCode)){
			productCodeStr = "富有代收付";
		}
		return productCodeStr;
	}

	/**
	 * 单笔充值接口
	 * @throws Exception 
	 */
	@Override
	public Map<String, String> singlePay(Map<String, Object> singlePayMap, String thirdProductCode) throws Exception {
		String requestOrderId = singlePayMap.get("requestOrderId").toString();
		String logInfo = "单笔支付订单订单" + requestOrderId + "-";
		
		String userIp = singlePayMap.get("userIp").toString();
		String userId = singlePayMap.get("userId").toString();
		String tradeAmount = singlePayMap.get("tradeAmount").toString();
		String bankAccountNo = singlePayMap.get("bankAccountNo").toString();
		
		UserInfo userInfo = userDao.getUserInfo(userId);
		
		String identityNo = userInfo.getId_card();
		String bankAccountName = userInfo.getReal_name();
		String phoneNumber = userInfo.getPhone_no();
		
		// 调用ThirdParty发起单笔支付
		Map<String, String> map = new HashMap<String, String>();
		map.put("userId", userId);
		map.put("requestOrderId", requestOrderId);
		map.put("tradeAmount", tradeAmount);
		map.put("productCode", thirdProductCode);
		map.put("bankAccountNo", bankAccountNo);
		map.put("bankAccountName", bankAccountName);
		map.put("identityNo", identityNo);
		map.put("phoneNumber", phoneNumber);
		map.put("userIp", userIp);
		
		Map<String, String> resMap = ThirdPartyEnvUtil.invoke(logInfo, map, "/route/singlePay");
		
		return resMap;
	}

	/**
	 * 查询卡bin接口
	 */
	@Override
	public Map<String, Object> cardBinQuery(Map<String, Object> cardBinQueryMap, String thirdProductCode)
			throws Exception {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String userId = cardBinQueryMap.get("userId").toString();
		String logInfo = "查询卡bin" + userId + "-";
		
		String thirdProductBankCode = cardBinQueryMap.get("thirdProductBankCode").toString();
		String cardNumber = cardBinQueryMap.get("cardNumber").toString();
		
		// 调用ThirdParty发起提现
		Map<String, String> map = new HashMap<String, String>();
		
		map.put("cardNumber", cardNumber);
		map.put("productCode", thirdProductCode);
		
		Map<String, String> resMap = ThirdPartyEnvUtil.invoke(logInfo, map, "/route/cardBinQuery");
		
		String resCode = resMap.get("rescode");
		String resMessage = resMap.get("resmsg_cn");
		
		if(resCode.equals("00001")){
			String object = resMap.get("object");
			JSONObject jsonObj = JSONObject.fromObject(object);
			
			String cardType = jsonObj.getString("cardType");
			String bankCode = jsonObj.getString("bankCode");
			
			if(cardType.equals("3")){
				resultMap.put("rescode", Consts.ERROR_CODE);
				resultMap.put("resmsg_cn", getErrorMessage(this.errorMessageService.getErrorMessage("CREDIT_NOT_SUPPORT")));
				return resultMap;
			}
			
			//判断联币平台是否支持该银行
			Map<String,String> queryBankInfo = new HashMap<String,String>();
			queryBankInfo.put("bankCode", bankCode);
			queryBankInfo.put("thirdPlatformCode", thirdProductBankCode);
			
			ThirdPlatformBank bank = this.thirdProductRouteDao.getThirdPlatformBankCode(queryBankInfo);
			
			if(bank==null){
				resultMap.put("rescode", Consts.CHECK_CODE);
				resultMap.put("resmsg_cn", getErrorMessage(this.errorMessageService.getErrorMessage("BANK_NOT_SUPPORT")));
				return resultMap;
			}
			
			
			resultMap.put("rescode", Consts.SUCCESS_CODE);
			resultMap.put("resmsg_cn", Consts.SUCCESS_DESCRIBE);
			resultMap.put("bankCode", bank.getBankCode());
			
		}else if(resCode.equals("00002")){
			resultMap.put("rescode", Consts.ERROR_CODE);
			resultMap.put("resmsg_cn", getErrorMessage(this.errorMessageService.getErrorMessage("BANK_CARD_NUMBER_ERROR")));
		}else{
			resultMap.put("rescode", Consts.CHECK_CODE);
			resultMap.put("resmsg_cn", getErrorMessage(this.errorMessageService.getErrorMessage("BANK_CARD_SYSTEM_ERROR")));
		}
		return resultMap;
	}

	/**
	 * 保存预支付订单信息
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	@Override
	public Map<String,Object> saveOrderInfoAndCard(Map<String,String> requestMap) throws Exception {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		String userId = requestMap.get("userId");
		String cardNumber = requestMap.get("cardNumber");
		String bankCode = requestMap.get("bankCode");
		String payFlag = requestMap.get("payFlag");
		String tradeAmount = requestMap.get("tradeAmount");
		
		User user = this.userDao.getUserDetail(userId);
		UserInfo userInfo = this.userDao.getUserInfo(userId);
		
		if(user==null || userInfo ==null){
			resultMap.put("rescode", Consts.ERROR_CODE);
			resultMap.put("resmsg_cn", getErrorMessage(this.errorMessageService.getErrorMessage("USER_NOT_EXIST")));
			return resultMap;
		}
		String acctName = userInfo.getReal_name();
		String idCard = userInfo.getId_card();
		String cardPhone = user.getMobile();
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("userId", userId);
		//查询用户是否存在绑定的银行卡
		List<UserRecePayCard> userCardList = this.userCardDao.queryUserCardInfoByUserId(paramMap);
		UserRecePayCard userRecePayCard = null;
		String reqOrderId = requestMap.get("reqOrderId");
		
		paramMap.put("cardNumber", cardNumber);
		paramMap.put("bankCode", bankCode);
		Bank bank = this.userCardDao.queryBankInfoByBankCode(paramMap);
		
		//查询支付的thirdProudctCode
		String productCode = "quick_singlepay";
		String bankName = bank.getBank_name();
		
		
		Map<String, String> queryRouteMap = new HashMap<String, String>();
		queryRouteMap.put("bankName", bankName);
		queryRouteMap.put("productCode", productCode);
		
		List<ThirdProductRoute> thirdProductRoutes = this.getThirdProductRoutes(queryRouteMap);
		
		if (thirdProductRoutes == null || thirdProductRoutes.size() == 0) {
			resultMap.put("rescode", Consts.ERROR_CODE);
			resultMap.put("resmsg_cn",getErrorMessage( this.errorMessageService.getErrorMessage("BUSINESSE_ERROR")));
			return resultMap;
		}
		
		int saveCardResultCount = 0;
		if(userCardList==null || userCardList.size() == 0){
			
			//查询数据库是否存在此银行卡信息
			
			userRecePayCard = this.userCardDao.queryBankCardByCardNo(paramMap);
			
			if(userRecePayCard == null ){
				userRecePayCard = new UserRecePayCard();
				userRecePayCard.setUser_id(Integer.parseInt(userId));
				userRecePayCard.setCard_number(cardNumber);
				// 查询银行信息进行保存
				userRecePayCard.setBank_id(bank.getId());
				userRecePayCard.setBank_name(bank.getBank_name());
				userRecePayCard.setIs_valid('N');
				userRecePayCard.setIs_binding('N');
				userRecePayCard.setCreate_time(new Date());
				userRecePayCard.setCreate_per(userId);
				userRecePayCard.setAccount_name(acctName);
				userRecePayCard.setReceive_certificate_type(1);
				userRecePayCard.setReceive_certificate_no(idCard);
				userRecePayCard.setMedia_type(1);
				userRecePayCard.setBinding_req_num(reqOrderId);
				userRecePayCard.setPhone_no(StringUtils.isNotBlank(cardPhone) ?cardPhone:"");
				
				userCardDao.saveUserBankCardInfo(userRecePayCard);
				
				Integer userCardId = userRecePayCard.getId();
				
				if(userCardId != null){
					saveCardResultCount = 1;
				}
			}else{
				// 查询银行信息进行保存
				userRecePayCard.setBank_id(bank.getId());
				userRecePayCard.setBank_name(bank.getBank_name());
				userRecePayCard.setIs_valid('N');
				userRecePayCard.setIs_binding('N');
				userRecePayCard.setUpdate_per(userId);
				userRecePayCard.setAccount_name(acctName);
				userRecePayCard.setReceive_certificate_no(idCard);
				userRecePayCard.setBinding_req_num(reqOrderId);
				
				saveCardResultCount = userCardDao.updateUserBankCardInfo(userRecePayCard);
			}
		}else{
			userRecePayCard = userCardList.get(0);
			userRecePayCard.setBinding_req_num(reqOrderId);
			userRecePayCard.setPhone_no(cardPhone);
			saveCardResultCount = this.userCardDao.updateUserBindindBankCardInfo(userRecePayCard);
		}
		
		if(saveCardResultCount <=0 ){
			resultMap.put("rescode", Consts.ERROR_CODE);
			resultMap.put("resmsg_cn", getErrorMessage(this.errorMessageService.getErrorMessage("SAVE_CARD_ERROR")));
			return resultMap;
		}
		
		/*
		 * 单笔支付
		 */
		
		ThirdProductRoute singlePayProductRoute = thirdProductRoutes.get(0);
		String singlePayThirdProductCode = singlePayProductRoute.getThirdProductCode(); 
		Map<String,Object> singlePayParamMap = new HashMap<String,Object>();
		singlePayParamMap.put("userId",userId);
		singlePayParamMap.put("requestOrderId", reqOrderId);
		singlePayParamMap.put("tradeAmount", tradeAmount);
		singlePayParamMap.put("bankAccountNo", cardNumber);
		singlePayParamMap.put("bankAccountName", acctName);
		singlePayParamMap.put("identityNo", idCard);
		singlePayParamMap.put("phoneNumber", cardPhone);
		
		Map<String,String> singlePayResultMap = this.singlePay(singlePayParamMap, singlePayThirdProductCode) ;
		
		//如果支付失败是否要回滚上面的代码？
		String rescode = singlePayResultMap.get("rescode");
		String message = singlePayResultMap.get("message");
		
		if (rescode.equals("00001")) {
			String sendMessage = singlePayResultMap.get("sendMessage");
			String resultObject = singlePayResultMap.get("object");
			String platform = singlePayProductRoute.getThirdPlatformCode().toUpperCase() + "PAY";
			String rechargeChannel = "";
			if(payFlag.equals("WY")){
				rechargeChannel = "WEB";
			}else{
				rechargeChannel = "MOBILE";
			}
			
			//保存预支付订单信息
			OrderFormRecharge orderFormRecharge = new OrderFormRecharge();
			orderFormRecharge.setAmount(new BigDecimal(tradeAmount));// 订单金额
			orderFormRecharge.setOrderform_id(reqOrderId);// 订单号
			orderFormRecharge.setRecharge_orderform_status("WAIT_BUYER_PAY");// 等待付款
			orderFormRecharge.setUser_id(Integer.parseInt(userId));// 所属用户
			orderFormRecharge.setSend_message(sendMessage);// 上送报文
			orderFormRecharge.setRechargetype("01");// 理财人类型
			orderFormRecharge.setAccounttype("01");// 个人主账户
			orderFormRecharge.setCore_status("CORE_WAIT");// 未调用核心，初始化状态
			orderFormRecharge.setRecharge_platform(platform);// 充值平台（UPAY:U付;SINAPAY:新浪支付;LIANLIANPAY:连连支付）
			orderFormRecharge.setSysuserid(Integer.parseInt(userId));// 操作员
			orderFormRecharge.setRecharge_channel(rechargeChannel);//充值渠道
			orderFormRecharge.setCardNumber(cardNumber);
			
			centerDao.createRechargeOrder(orderFormRecharge);
			
			JSONObject resultJson = JSONObject.fromObject(resultObject);
			
			String merId = resultJson.getString("merid");
			String returnObj = resultJson.getString("object");
			String orderTime = resultJson.getString("orderTime");
			// 购买参数表设置
			FastPayTokenParamters fastPayTokenParamters = new FastPayTokenParamters();
			fastPayTokenParamters.setTradeOrderId(reqOrderId);
			fastPayTokenParamters.setMerNo(merId);
			fastPayTokenParamters.setTrDt(orderTime);
			fastPayTokenParamters.setBuyAmount(tradeAmount);
			String paramterJson = JsonUtil
					.getJsonStringFromObject(fastPayTokenParamters);

			PayParamtersTemp paramtersBean = new PayParamtersTemp();
			paramtersBean.setCreate_per(userId);
			paramtersBean.setParameter_str(paramterJson);
			paramtersBean.setPlatform_en_name(platform);
			paramtersBean.setReq_orderid(reqOrderId);
			paramtersBean.setUpdate_per(userId);

			payDao.addPayParameter(paramtersBean);
			
			resultMap.put("rescode", Consts.SUCCESS_CODE);
			resultMap.put("resmsg_cn", Consts.SUCCESS_DESCRIBE);
			resultMap.put("payObj", returnObj);
			resultMap.put("rechargeChannel", rechargeChannel);
			
		}else if (rescode.equals("00002")) {
			resultMap.put("rescode", Consts.ERROR_CODE);
			resultMap.put("resmsg_cn", getErrorMessage(this.errorMessageService.getErrorMessage("SAVE_CARD_ERROR")));
			return resultMap;
		}else if (rescode.equals("00004")) {
			resultMap.put("rescode", Consts.CHECK_CODE);
			resultMap.put("resmsg_cn",getErrorMessage(this.errorMessageService.getErrorMessage("SAVE_CARD_ERROR")));
			return resultMap;
		}
		
		return resultMap;
	}
	
	/**
	 * 保存银行卡信息
	 */
	@Override
	public Map<String, Object> saveCardInfo(Map<String, String> requestMap) throws Exception {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		String userId = requestMap.get("userId");
		String cardNumber = requestMap.get("cardNumber");
		String bankCode = requestMap.get("bankCode");
		String mobile = requestMap.get("mobile");
		
		Map<String,Object> queryMap = new HashMap<String,Object>();
		queryMap.put("userId", userId);
		queryMap.put("mobile", mobile);
		User user = this.userDao.getUserDetail(userId);
		UserInfo userInfo = this.userDao.getUserInfo(userId);
		
		if(user==null || userInfo ==null){
			resultMap.put("rescode", Consts.ERROR_CODE);
			resultMap.put("resmsg_cn", getErrorMessage(this.errorMessageService.getErrorMessage("USER_NOT_EXIST")));
			return resultMap;
		}
		
		if (!"Y".equals(user.getIdcard_validate()) ||  !"1".equals(user.getIs_create_acct())) {
			resultMap.put("rescode", Consts.ERROR_CODE);
			resultMap.put("resmsg_cn", getErrorMessage(this.errorMessageService.getErrorMessage("AUTHENTICATION_IS_NOT")));
			return resultMap;
		}
		String acctName = userInfo.getReal_name();
		String idCard = userInfo.getId_card();
		String cardPhone = mobile;
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("userId", userId);
		//查询用户是否存在绑定的银行卡
		UserRecePayCard userRecePayCard = null;
		String reqOrderId = requestMap.get("reqOrderId");
		
		paramMap.put("cardNumber", cardNumber);
		paramMap.put("bankCode", bankCode);
		Bank bank = this.userCardDao.queryBankInfoByBankCode(paramMap);
		
		
		int saveCardResultCount = 0;
			
		//查询数据库是否存在此银行卡信息
		
		userRecePayCard = this.userCardDao.queryBankCardByCardNo(paramMap);
		
		if(userRecePayCard == null ){
			userRecePayCard = new UserRecePayCard();
			userRecePayCard.setUser_id(Integer.parseInt(userId));
			userRecePayCard.setCard_number(cardNumber);
			// 查询银行信息进行保存
			userRecePayCard.setBank_id(bank.getId());
			userRecePayCard.setBank_name(bank.getBank_name());
			userRecePayCard.setIs_valid('N');
			userRecePayCard.setIs_binding('N');
			userRecePayCard.setCreate_time(new Date());
			userRecePayCard.setCreate_per(userId);
			userRecePayCard.setAccount_name(acctName);
			userRecePayCard.setReceive_certificate_type(1);
			userRecePayCard.setReceive_certificate_no(idCard);
			userRecePayCard.setMedia_type(1);
			userRecePayCard.setBinding_req_num(reqOrderId);
			userRecePayCard.setPhone_no(StringUtils.isNotBlank(cardPhone) ?cardPhone:"");
			
			userCardDao.saveUserBankCardInfo(userRecePayCard);
			
			Integer userCardId = userRecePayCard.getId();
			
			if(userCardId != null){
				saveCardResultCount = 1;
			}
		}else{
			// 查询银行信息进行保存
			userRecePayCard.setBank_id(bank.getId());
			userRecePayCard.setBank_name(bank.getBank_name());
			userRecePayCard.setIs_valid('N');
			userRecePayCard.setIs_binding('N');
			userRecePayCard.setUpdate_per(userId);
			userRecePayCard.setAccount_name(acctName);
			userRecePayCard.setReceive_certificate_no(idCard);
			userRecePayCard.setBinding_req_num(reqOrderId);
			userRecePayCard.setPhone_no(StringUtils.isNotBlank(cardPhone) ?cardPhone:"");
			
			saveCardResultCount = userCardDao.updateUserBankCardInfo(userRecePayCard);
		}
		
		
		if(saveCardResultCount <=0 ){
			resultMap.put("rescode", Consts.ERROR_CODE);
			resultMap.put("resmsg_cn", getErrorMessage(this.errorMessageService.getErrorMessage("SAVE_CARD_ERROR")));
			return resultMap;
		}
		
		resultMap.put("rescode", Consts.SUCCESS_CODE);
		resultMap.put("resmsg_cn", Consts.SUCCESS_DESCRIBE);
		
		return resultMap;
	}
	
	/**
	 * 保存预支付订单信息
	 */
	@Override
	public Map<String, Object> saveOrderInfo(Map<String, String> requestMap) throws Exception {
		
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		String userId = requestMap.get("userId");
		String cardNumber = requestMap.get("cardNumber");
		String payFlag = requestMap.get("payFlag");
		String tradeAmount = requestMap.get("tradeAmount");
		String userIp = requestMap.get("userIp");
		String bankName = requestMap.get("bankName");
		
		User user = this.userDao.getUserDetail(userId);
		UserInfo userInfo = this.userDao.getUserInfo(userId);
		
		if(user==null || userInfo ==null){
			resultMap.put("rescode", Consts.ERROR_CODE);
			resultMap.put("resmsg_cn", getErrorMessage(this.errorMessageService.getErrorMessage("USER_NOT_EXIST")));
			return resultMap;
		}
		String acctName = userInfo.getReal_name();
		String idCard = userInfo.getId_card();
		String cardPhone = user.getMobile();
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("userId", userId);
		//查询用户是否存在绑定的银行卡
		String reqOrderId = requestMap.get("reqOrderId");
		
		
		String singlePayThirdProductCode = requestMap.get("singlePayProductRoute").toString();
		Map<String,Object> singlePayParamMap = new HashMap<String,Object>();
		singlePayParamMap.put("userId",userId);
		singlePayParamMap.put("requestOrderId", reqOrderId);
		singlePayParamMap.put("tradeAmount", tradeAmount);
		singlePayParamMap.put("bankAccountNo", cardNumber);
		singlePayParamMap.put("bankAccountName", acctName);
		singlePayParamMap.put("identityNo", idCard);
		singlePayParamMap.put("phoneNumber", cardPhone);
		singlePayParamMap.put("userIp", userIp);
		
		Map<String,String> singlePayResultMap = this.singlePay(singlePayParamMap, singlePayThirdProductCode) ;
		
		//如果支付失败是否要回滚上面的代码？
		String rescode = singlePayResultMap.get("rescode");
		
		if (rescode.equals("00001")) {
			String sendMessage = singlePayResultMap.get("sendMessage");
			String resultObject = singlePayResultMap.get("object");
			String thirdPlatformCode = requestMap.get("thirdPlatformCode").toString();
			String platform = thirdPlatformCode.toUpperCase() + "PAY";
			String rechargeChannel = "";
			if(payFlag.equals("WY")){
				rechargeChannel = "WEB";
			}else{
				rechargeChannel = "MOBILE";
			}
			
			//保存预支付订单信息
			OrderFormRecharge orderFormRecharge = new OrderFormRecharge();
			orderFormRecharge.setAmount(new BigDecimal(tradeAmount));// 订单金额
			orderFormRecharge.setOrderform_id(reqOrderId);// 订单号
			orderFormRecharge.setRecharge_orderform_status("WAIT_BUYER_PAY");// 等待付款
			orderFormRecharge.setUser_id(Integer.parseInt(userId));// 所属用户
			orderFormRecharge.setSend_message(sendMessage);// 上送报文
			orderFormRecharge.setRechargetype("01");// 理财人类型
			orderFormRecharge.setAccounttype("01");// 个人主账户
			orderFormRecharge.setCore_status("CORE_WAIT");// 未调用核心，初始化状态
			orderFormRecharge.setRecharge_platform(platform);// 充值平台（UPAY:U付;SINAPAY:新浪支付;LIANLIANPAY:连连支付）
			orderFormRecharge.setSysuserid(Integer.parseInt(userId));// 操作员
			orderFormRecharge.setRecharge_channel(rechargeChannel);//充值渠道
			orderFormRecharge.setCardNumber(cardNumber);
			orderFormRecharge.setBankName(bankName);
			
			centerDao.createRechargeOrder(orderFormRecharge);
			
			JSONObject resultJson = JSONObject.fromObject(resultObject);
			
			String returnObj = resultJson.getString("object");
			String sendUrl = resultJson.getString("sendUrl");
			String method = resultJson.getString("method");
			
			resultMap.put("rescode", Consts.SUCCESS_CODE);
			resultMap.put("resmsg_cn", Consts.SUCCESS_DESCRIBE);
			resultMap.put("payObj", returnObj);
			resultMap.put("platform", platform);
			resultMap.put("sendUrl", sendUrl);
			resultMap.put("method", method);
			
		}else if (rescode.equals("00002")) {
			resultMap.put("rescode", Consts.ERROR_CODE);
			resultMap.put("resmsg_cn", getErrorMessage(this.errorMessageService.getErrorMessage("SAVE_CARD_ERROR")));
			return resultMap;
		}else if (rescode.equals("00004")) {
			resultMap.put("rescode", Consts.CHECK_CODE);
			resultMap.put("resmsg_cn",getErrorMessage(this.errorMessageService.getErrorMessage("SAVE_CARD_ERROR")));
			return resultMap;
		}
		
		return resultMap;
	}
	
	
	public String getErrorMessage(Map<String,Object> errorMessageMap){
		ErrorMessageSetting ems = (ErrorMessageSetting) errorMessageMap.get("errorMessage");
		String messageContent =  ems.getMessage_content();
		return messageContent;
	}

	/**
	 * 单笔支付回调方法
	 */
	@Override
	public Map<String, Object> singlePayNotify(Map<String, Object> requestMap) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String bindingReqNum = requestMap.get("reqOrderId").toString();
		String payFlag = requestMap.get("payFlag")==null?null:requestMap.get("payFlag").toString();
		
		String moneyOrder = requestMap.get("tradeAmount").toString();
		String oidPayBill = requestMap.get("resOrderId").toString();
		String reqStr = requestMap.get("receiveMessage").toString();
		
		String transCode = "E330033";
		Map<String, Object> coreMap = new HashMap<String, Object>();
		
		coreMap.put("bindingReqNum", bindingReqNum);
		coreMap.put("moneyOrder", moneyOrder);
		coreMap.put("oidPayBill", oidPayBill);
		coreMap.put("reqStr", reqStr);
		
		if(StringUtils.isNotBlank(payFlag)){
			coreMap.put("payFlag", payFlag);
		}
		
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		String userId = "";
		try{
			//如果核心访问失败 返回连连成功（不需要连连继续回调）
			JSONObject jsonObject = JSONObject.fromObject(rtnStr);
			resultMap.put("rescode", jsonObject.getString("rescode"));
			resultMap.put("resmsg_cn", jsonObject.getString("resmsg"));
			userId = jsonObject.getString("userId");
			resultMap.put("userId", jsonObject.getString("userId"));
		}catch(Exception e){
			resultMap.put("rescode", Consts.SUCCESS_CODE);
			resultMap.put("resmsg_cn", Consts.SUCCESS_DESCRIBE);
		}
		
		return resultMap;
	}
	
	@Override
	public Map<String, String> apiPrePayment(Map<String, Object> singlePayMap, String thirdProductCode)
			throws Exception {
		String requestOrderId = singlePayMap.get("requestOrderId").toString();
		String logInfo = "单笔支付订单订单" + requestOrderId + "-";
		
		String userIp = singlePayMap.get("userIp").toString();
		String userId = singlePayMap.get("userId").toString();
		String tradeAmount = singlePayMap.get("tradeAmount").toString();
		String bankAccountNo = singlePayMap.get("bankAccountNo").toString();
		
		UserInfo userInfo = userDao.getUserInfo(userId);
		
		String identityNo = userInfo.getId_card();
		String bankAccountName = userInfo.getReal_name();
		String phoneNumber = singlePayMap.get("phoneNumber").toString();
		
		// 调用ThirdParty发起单笔支付
		Map<String, String> map = new HashMap<String, String>();
		map.put("userId", userId);
		map.put("requestOrderId", requestOrderId);
		map.put("tradeAmount", tradeAmount);
		map.put("productCode", thirdProductCode);
		map.put("bankAccountNo", bankAccountNo);
		map.put("bankAccountName", bankAccountName);
		map.put("identityNo", identityNo);
		map.put("phoneNumber", phoneNumber);
		map.put("userIp", userIp);
		
		Map<String, String> resMap = ThirdPartyEnvUtil.invoke(logInfo, map, "/route/apiPrePayment");
		
		return resMap;
	}
	
	@Override
	public Map<String, String> apiCheckPayment(Map<String, Object> singlePayMap, String thirdProductCode)
			throws Exception {
		String requestOrderId = singlePayMap.get("requestOrderId").toString();
		String logInfo = "单笔支付订单订单" + requestOrderId + "-";
		
		String userId = singlePayMap.get("userId").toString();
		String checkCode = singlePayMap.get("checkCode").toString();
		String payToken = singlePayMap.get("payToken").toString();
		String resOrderId = singlePayMap.get("resOrderId").toString();
		String bankAccountNo = singlePayMap.get("bankAccountNo").toString();
		String phoneNumber = singlePayMap.get("phoneNumber").toString();
		String userIp = singlePayMap.get("userIp").toString();
		
		
		// 调用ThirdParty发起单笔支付
		Map<String, String> map = new HashMap<String, String>();
		map.put("userId", userId);
		map.put("requestOrderId", requestOrderId);
		map.put("productCode", thirdProductCode);
		map.put("checkCode", checkCode);
		map.put("payToken", payToken);
		map.put("bankAccountNo", bankAccountNo);
		map.put("resOrderId", resOrderId);
		map.put("phoneNumber", phoneNumber);
		map.put("userIp", userIp);
		
		Map<String, String> resMap = ThirdPartyEnvUtil.invoke(logInfo, map, "/route/apiCheckPayment");
		
		return resMap;
	}
	
	@Override
	public ResultDTO<Map<String,Object>> saveApiOrderInfo(Map<String, String> requestMap) throws Exception {
		ResultDTO<Map<String,Object>> resultDTO = null;
		
		String userId = requestMap.get("userId");
		String cardNumber = requestMap.get("cardNumber");
		String payFlag = requestMap.get("payFlag");
		String tradeAmount = requestMap.get("tradeAmount");
		String userIp = requestMap.get("userIp");
		String bankName = requestMap.get("bankName");
		String mobile = requestMap.get("mobile");
		
		User user = this.userDao.getUserDetail(userId);
		UserInfo userInfo = this.userDao.getUserInfo(userId);
		
		if(user==null || userInfo ==null){
			
			resultDTO =  new ResultDTO<Map<String,Object>>(ResultCode.FAILED,
						Message.CnDescriptionExpression.USER_NOT_EXIST);
			return resultDTO;
		}
		String acctName = userInfo.getReal_name();
		String idCard = userInfo.getId_card();
		String cardPhone = mobile;
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("userId", userId);
		String reqOrderId = requestMap.get("reqOrderId");
		
		
		String singlePayThirdProductCode = requestMap.get("singlePayProductRoute").toString();
		Map<String,Object> singlePayParamMap = new HashMap<String,Object>();
		singlePayParamMap.put("userId",userId);
		singlePayParamMap.put("requestOrderId", reqOrderId);
		singlePayParamMap.put("tradeAmount", tradeAmount);
		singlePayParamMap.put("bankAccountNo", cardNumber);
		singlePayParamMap.put("bankAccountName", acctName);
		singlePayParamMap.put("identityNo", idCard);
		singlePayParamMap.put("phoneNumber", cardPhone);
		singlePayParamMap.put("userIp", userIp);
		
		Map<String,String> singlePayResultMap = this.apiPrePayment(singlePayParamMap, singlePayThirdProductCode) ;
		
		//如果支付失败是否要回滚上面的代码？
		String rescode = singlePayResultMap.get("rescode");
		String message = singlePayResultMap.get("message");
		if (rescode.equals("00001")) {
			String sendMessage = singlePayResultMap.get("sendMessage");
			String resultObject = singlePayResultMap.get("object");
			String resOrderId = singlePayResultMap.get("resOrderId");
			String thirdPlatformCode = requestMap.get("thirdPlatformCode").toString();
			String platform = thirdPlatformCode.toUpperCase() + "PAY";
					
			String rechargeChannel = "";
			if(payFlag.equals("WY")){
				rechargeChannel = "WEB";
			}else{
				rechargeChannel = "MOBILE";
			}
			
			//保存预支付订单信息
			OrderFormRecharge orderFormRecharge = new OrderFormRecharge();
			orderFormRecharge.setAmount(new BigDecimal(tradeAmount));// 订单金额
			orderFormRecharge.setOrderform_id(reqOrderId);// 订单号
			orderFormRecharge.setRecharge_orderform_status("WAIT_BUYER_PAY");// 等待付款
			orderFormRecharge.setUser_id(Integer.parseInt(userId));// 所属用户
			orderFormRecharge.setSend_message(sendMessage);// 上送报文
			orderFormRecharge.setRechargetype("01");// 理财人类型
			orderFormRecharge.setAccounttype("01");// 个人主账户
			orderFormRecharge.setCore_status("CORE_WAIT");// 未调用核心，初始化状态
			orderFormRecharge.setRecharge_platform(platform);// 充值平台（UPAY:U付;SINAPAY:新浪支付;LIANLIANPAY:连连支付）
			orderFormRecharge.setSysuserid(Integer.parseInt(userId));// 操作员
			orderFormRecharge.setRecharge_channel(rechargeChannel);//充值渠道
			orderFormRecharge.setCardNumber(cardNumber);
			orderFormRecharge.setBankName(bankName);
			
			centerDao.createRechargeOrder(orderFormRecharge);
			
			JSONObject resultJson = JSONObject.fromObject(resultObject);
			
			String payToken = resultJson.getString("payToken");
			Map<String,Object> resultMap = new HashMap<String,Object>();
			resultMap.put("payToken", payToken);
			resultMap.put("platform", platform);
			resultMap.put("reqOrderId", reqOrderId);
			resultMap.put("resOrderId", resOrderId);
			resultMap.put("bankName", bankName);
			resultMap.put("phoneNumber", cardPhone);
			resultMap.put("bankAccountNo", cardNumber);
			
			resultDTO = new ResultDTO<>(ResultCode.SUCCESS, Consts.SUCCESS_DESCRIBE);
			
			resultDTO.setRecord(resultMap);
			
		}else if (rescode.equals("00002")) {
			resultDTO =  new ResultDTO<Map<String,Object>>(ResultCode.FAILED,
					message);
			return resultDTO;
			
		}else if (rescode.equals("00004")) {
			resultDTO =  new ResultDTO<Map<String,Object>>(ResultCode.FAILED,
					message);
			return resultDTO;
		}
		
		return resultDTO;
	}
	
	
	/**
	 * 检查API支付接口验证码方法
	 */
	@Override
	public ResultDTO<Map<String,Object>> apiCheckCode(Map<String, String> requestMap) throws Exception {
		
		ResultDTO<Map<String,Object>> resultDTO = null;
		
		String userId = requestMap.get("userId");
		String requestOrderId = requestMap.get("requestOrderId");
		String checkCode = requestMap.get("checkCode");
		String payToken = requestMap.get("payToken");
		String resOrderId = requestMap.get("resOrderId");
		String bankAccountNo = requestMap.get("bankAccountNo");
		String phoneNumber = requestMap.get("phoneNumber");
		String userIp = requestMap.get("userIp");
		
		Map<String,Object> apiCheckCodeParamMap = new HashMap<String,Object>();
		apiCheckCodeParamMap.put("userId",userId);
		apiCheckCodeParamMap.put("requestOrderId", requestOrderId);
		apiCheckCodeParamMap.put("checkCode", checkCode);
		apiCheckCodeParamMap.put("payToken", payToken);
		apiCheckCodeParamMap.put("resOrderId", resOrderId);
		apiCheckCodeParamMap.put("bankAccountNo", bankAccountNo);
		apiCheckCodeParamMap.put("phoneNumber", phoneNumber);
		apiCheckCodeParamMap.put("userIp", userIp);
		
		
		String checkCodeThirdProductCode = requestMap.get("checkCodeThirdProductCode").toString();
		
		Map<String,String> checkCodeResultMap = this.apiCheckPayment(apiCheckCodeParamMap, checkCodeThirdProductCode);
		
		String rescode = checkCodeResultMap.get("rescode");
		
		if (rescode.equals("00001")) {
			resultDTO = new ResultDTO<>(ResultCode.SUCCESS, Consts.SUCCESS_DESCRIBE);
		}else{
			String message = checkCodeResultMap.get("message");
			resultDTO =  new ResultDTO<>(ResultCode.FAILED,
					message);
			return resultDTO;
		}
		
		return resultDTO;
	}
	
	/**
	 * 单笔支付回调 新接口
	 */
	@Override
	public ResultDTO<Map<String, Object>> singlePayNotifyNew(Map<String, Object> requestMap) throws Exception {
		
		Map<String, Object> resultMap = this.singlePayNotify(requestMap);
		String rescode = resultMap.get("rescode").toString();
		
		ResultDTO<Map<String,Object>> resultDTO = null;
		
		if(rescode.equals(Consts.SUCCESS_CODE)){
			resultDTO = new ResultDTO<>(ResultCode.SUCCESS, Consts.SUCCESS_DESCRIBE);
			String userId = resultMap.get("userId")==null?"":resultMap.get("userId").toString();
			String tradeAmount = requestMap.get("tradeAmount").toString();
			//发送短信或微信
			sendMeidaAndSMS(userId,new HashMap<String,String>(), tradeAmount);
			//发送个推消息----add by gongyanlan
			String smsNo="sms01001";//充值,config_sms表中参数,
			String mobile = captchaService.getMobileById(userId);//通过用户ID查询使用手机号
			String[] smsParams={tradeAmount,"",""};
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("userId", userId);
			map.put("mobile", mobile);
			map.put("title", "充值成功通知");//标题
			map.put("messageDetailTypeNew", "3");//1.订制商品个人消息，2.还款成功，3.充值，4.投资，5,提现
			map.put("messageDetailResult", "0");//0.执行成功消息提示，1.执行失败提示
			map.put("smsParams", smsParams);//消息模板里需要替换的变量
			map.put("smsNo", smsNo);
			sMSService.sendGetuiMSG(map);
		}else if("99998".equals(rescode)){
			resultDTO = new ResultDTO<>(ResultCode.SUCCESS, Consts.SUCCESS_DESCRIBE);
		}else{
			String resmsg = resultMap.get("resmsg_cn").toString();
			resultDTO =  new ResultDTO<>(ResultCode.FAILED,
					resmsg);
		}
		
		return resultDTO;
	}
	
	/**
	 * 查询银行路由列表接口
	 */
	@Override
	public ResultDTO<Map<String,String>> queryRouteBankList(Map<String, Object> requestMap) throws Exception {
		
		ResultDTO<Map<String, String>> resultDTO = new ResultDTO<>(ResultCode.SUCCESS, Consts.SUCCESS_DESCRIBE);
		
		// 查询银行列表
		List<Map<String, String>> bankList = this.bankDao.queryRouteBankList(requestMap);
		
		if(bankList==null){
			bankList = new ArrayList<Map<String,String>>();
		}
		resultDTO.setRecords(bankList);
		resultDTO.setTotal(bankList.size());
		
		return resultDTO;
	}
	
	/**
	 * 根据USERID发送短信/微信
	 * @param userId
	 */
	public void sendMeidaAndSMS(String userId,Map<String,String> paramsMap,String moneyOrder) throws Exception{
		//封装用户ID
		WeixinMediaBinding mediaBinding = new WeixinMediaBinding();
		mediaBinding.setUserId(Integer.parseInt(userId));
		
		//先推送微信，微信成功不发短信，失败再发短信
		String mobile = captchaService.getMobileById(userId);//通过用户ID查询使用手机号
		String mediaUid = weixinBindingService.queryMediaUid(mediaBinding);//通过用户ID实体类查询微信标识
		
		//TODO 逻辑判断
		if(null == mediaUid || "null".equalsIgnoreCase(mediaUid) || "".equalsIgnoreCase(mediaUid)){
			logger.info("[推送短信息]因手机号："+mobile+"并未绑定微信");
			//发送短信
			String cpType="";
			String smsNo="sms01001";//config_sms表中参数
			String tsje=moneyOrder;
			if (StringUtils.isBlank(userId) 
					|| StringUtils.isBlank(smsNo)|| StringUtils.isBlank(tsje)) {
				logger.debug("deposit/join sendSMS 传入参数为空");
			}
			try{
				// 发送短信
				if(StringUtils.isEmpty(cpType)){
					 sMSService.getSMS(userId,smsNo,tsje);	
				}else{
					sMSService.getSMS(userId,smsNo,tsje,cpType);	
				}
			} catch (Exception e) {
				logger.error("deposit/join sendSMS异常:" + e.getCause());
			}
		}else{
			Map<String,String> weixinTMap = new HashMap<String,String>();
			weixinTMap.put("mediaUid", mediaUid);//微信用户唯一标识 
			weixinTMap.put("money", moneyOrder);//充值金额
			weixinTMap.put("functionScope", "recharge");//推送类型
			
			boolean sendRusult = SendWeiXinUtil.sendWeiXin(weixinTMap);
			if(!sendRusult){
				logger.info("[微信推送失败][推送短信息]因手机号："+mobile+"并未绑定微信或者未关注联币钱包微信号");
				//发送短信
				String cpType="";
				String smsNo="sms01001";//config_sms表中参数
				String tsje=moneyOrder;
				if (StringUtils.isBlank(userId) 
						|| StringUtils.isBlank(smsNo)|| StringUtils.isBlank(tsje)) {
					logger.debug("deposit/join sendSMS 传入参数为空");
				}
				try{
					// 发送短信
					if(StringUtils.isEmpty(cpType)){
						 sMSService.getSMS(userId,smsNo,tsje);	
					}else{
						sMSService.getSMS(userId,smsNo,tsje,cpType);	
					}
				} catch (Exception e) {
					logger.error("deposit/join sendSMS异常:" + e.getCause());
				}
			}else{
				logger.info("[微信推送]手机号："+mobile+"推送成功");
			}
		}
	}
	
	/**
	 * 更新用户银行卡预留手机号信息
	 */
	@Override
	public ResultDTO saveCardPhoneNumber(Map<String, String> requestMap) throws Exception {
		ResultDTO resultDTO = null;
		
		String userId = requestMap.get("userId");
		String cardNumber = requestMap.get("cardNumber");
		String mobile = requestMap.get("mobile");
		
		User user = this.userDao.getUserDetail(userId);
		
		if (!"Y".equals(user.getIdcard_validate()) ||  !"1".equals(user.getIs_create_acct())) {
			resultDTO = new ResultDTO<>(ResultCode.FAILED,
					getErrorMessage(this.errorMessageService.getErrorMessage("AUTHENTICATION_IS_NOT")));
			return resultDTO;
		}
		
		Map<String, Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("userId", userId);
		paramsMap.put("cardNumber", cardNumber);
		paramsMap.put("mobile", mobile);
		
		UserRecePayCard userCard =  this.userCardDao.queryBankCardByCardNo(paramsMap);
		
		if(userCard==null){
			resultDTO = new ResultDTO<>(ResultCode.FAILED,
					getErrorMessage(this.errorMessageService.getErrorMessage("BINGINGCARD_NOT_EXIST")));
			return resultDTO;
		}
		
		String isBinding = String.valueOf(userCard.getIs_binding());
		if(!isBinding.equals("Y")){
			resultDTO = new ResultDTO<>(ResultCode.FAILED,
					getErrorMessage(this.errorMessageService.getErrorMessage("BINGINGCARD_NOT_EXIST")));
			return resultDTO;
		}
		
		
		userCard.setPhone_no(mobile);
		
		int resultCount = this.userCardDao.updateUserBindindBankCardInfo(userCard);
		
		if(resultCount<1){
			resultDTO = new ResultDTO<>(ResultCode.FAILED,
					getErrorMessage(this.errorMessageService.getErrorMessage("SAVE_CARD_ERROR")));
			return resultDTO;
		}else{
			resultDTO = new ResultDTO<>(ResultCode.SUCCESS, Consts.SUCCESS_DESCRIBE);
		}
		return resultDTO;
	}
}